package com.wstuo.itsm.cim.QRCodeUtil;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.wstuo.common.config.server.dto.ServerUrlDTO;
import com.wstuo.common.config.server.service.IServerUrlService;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.util.StringUtils;
import com.wstuo.itsm.cim.dto.CIScanDTO;
import com.wstuo.itsm.cim.service.ICIService;
/**
 * 二维码生成管理方法
 * @author QXY
 *
 */
public class QRCode {
	private static final Logger LOGGER = Logger.getLogger(QRCode.class);
	@Autowired
	private AppContext appctx;
	@Autowired
    private ICIService ciService;
	@Autowired
	private IServerUrlService serverUrlService;
	/**
	 * 生成二维码的方法 
	 * @param sdto
	 * @param ciScanDTO
	 * @return String
	 */
	public boolean encode(ServerUrlDTO sdto,CIScanDTO ciScanDTO) {
		String ORCODEIMG_PATH =  AppConfigUtils.getInstance().getQRCodePath();
		boolean boo=true;
		try {
	        String str=sdto.getUrlName()+"/pages/itsm/cim/CiScan.jsp?id="+ciScanDTO.getCiId();
			String path = ORCODEIMG_PATH+"//img_"+ciScanDTO.getCiId()+".png";
			File frlFile = new File( path );
            //删除文件
            if ( frlFile.exists()){
                frlFile.delete();
            }
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();  
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//使用小写的编码，大写会出现]Q2\000026开头内容
			//ErrorCorrectionLevel.H 容错率：容错率越高,二维码的有效像素点就越多.
	        hints.put(EncodeHintType.MARGIN,1);//margin 边框设置
	        hints.put(EncodeHintType.MIN_SIZE, 70);
	        hints.put(EncodeHintType.MAX_SIZE, 70);
	        //编码内容,编码类型(这里指定为二维码),生成图片宽度,生成图片高度,设置参数    
	        BitMatrix bitMatrix = null;    
	        bitMatrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, 586, 70, hints);
			//File file = new File(path);

			MatrixToImageWriter.writeToFile(bitMatrix, "png", frlFile);
		
			createCiTagImg(frlFile,ciScanDTO);
				
		} catch (Exception e) {
			LOGGER.error(e);
		}
		return boo;
	}
	
	/**
	 * 生成配置项标签的方法
	 *     Image.SCALE_SMOOTH 的缩略算法  生成缩略图片的平滑度的  
     *     优先级比速度高 生成的图片质量比较好 但速度慢  
	 * @param file 生成的二维码路径
	 * @param ciScanDTO 配置项实体
	 * @throws IOException
	 */
    public void createCiTagImg(File file, CIScanDTO ciScanDTO) throws IOException{
        
        BufferedImage biRead = ImageIO.read(file);
        Image image = biRead;
        BufferedImage bi = new BufferedImage(330, biRead.getHeight(), BufferedImage.SCALE_SMOOTH);   
        /**
         * 读取二维码图片，并构建绘图对象
         */
        Graphics2D g2D = (Graphics2D)bi.getGraphics();   
        g2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g2D.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2D.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
        //设置字体颜色
        g2D.drawImage(image, 0, 0, null);//
        g2D.setFont(new Font("宋体",15,16));
        g2D.setColor(Color.black); 
        LanguageContent lc = LanguageContent.getInstance();
        String lang = appctx.getCurrentLanguage();
        
        g2D.drawString(lc.getContent("title.asset.name", lang), 2, 21);
       // g2D.drawString("I       P", 2, 42);
        g2D.drawString(lc.getContent("ci.use", lang), 2, 61);
        
        g2D.drawString(":", 110, 21);
       // g2D.drawString(":", 110, 42);
        g2D.drawString(":", 110, 61);
        
        // 标签 配置项名长度控制
        String name=ciScanDTO.getCiname();
        if(StringUtils.hasText(name) && ciScanDTO.getCiname().length()>9){
            name = StringUtils.cutStr(ciScanDTO.getCiname(), 8,StringUtils.ELLIPSIS);
        }
        String userName = "";
        if(StringUtils.hasText(ciScanDTO.getUserName())){
        	userName =ciScanDTO.getUserName();
        }
        String ip = "";
        if(StringUtils.hasText(ciScanDTO.getNetWork_ip())){
        	ip = ciScanDTO.getNetWork_ip();
        }
        //开始绘制图片，写入配置项名称、ip等
        g2D.drawString(name, 120, 21);
        //g2D.drawString(ip, 120, 42);
        g2D.drawString(userName, 120, 61);
        
        ImageIO.write(bi, "png", file);
    }
    
	/**
	 * 图片读取
	 * @param strNum
	 * @return String
	 */
	public InputStream encodeImage(Long strNum) {
		String ORCODEIMG_PATH =  AppConfigUtils.getInstance().getQRCodePath();
		InputStream imageStream = null;
		try {
			if(strNum!=0){ 
				String pathimg = ORCODEIMG_PATH+"/img_"+strNum+".png";
				File fileImg = new File(pathimg);
				//if(!fileImg.exists()){
					CIScanDTO ciScanDTO= ciService.findConfigureItemByCIID(strNum);
					ServerUrlDTO sdto= serverUrlService.findServiceUrl();
					encode(sdto,ciScanDTO);
				//}
				imageStream=new FileInputStream(fileImg);
				
			}
			
		} catch (Exception e) {
			LOGGER.error(e);
		}
		return imageStream;
	}

}
